package action;

import config.ApplicationConfig;
import server.VerificationCodeServer;
import util.VerificationCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedHashMap;

/**
 * User: tum0r
 * Package Name: ${PACKAGE_NAME}
 * Time: 2019-03-10 Sunday 15:13:29
 */
public class VerificationCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LinkedHashMap<String, String> pageConfig = ApplicationConfig.readConfig("page.json");
        request.setCharacterEncoding(pageConfig.get("encode"));
        response.setCharacterEncoding(pageConfig.get("encode"));

        VerificationCodeServer verificationCodeServer = new VerificationCodeServer();
        verificationCodeServer.open();
        HttpSession session = request.getSession();
        Object oldCookie = session.getAttribute("cookie");
        if (oldCookie != null&&!oldCookie.toString().equals("")) {
            verificationCodeServer.deleteVerificationCode(oldCookie.toString());
        }
        String cookie = verificationCodeServer.setCookie();
        session.setAttribute("cookie", cookie);
        String verCode = verificationCodeServer.getVerificationCode(cookie);
        verificationCodeServer.close();

        VerificationCode verificationCode = new VerificationCode();
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        os.write(verificationCode.getVerificationCodeByteArray(verCode));
        os.flush();
        os.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
